package github.sf.fw.hbase;


import github.sf.fw.tools.db.model.ResultData;
import github.sf.fw.tools.db.model.ResultRow;
import github.sf.fw.utils.ByteUtil;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class HBaseUtils {
    public static String rowKey() {
        long l = System.currentTimeMillis();
        return l + "_" + randString(4);
    }

    private static String randString(int n) {
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder(n);
        for (int i = 0; i < n; i++) {
            int i1 = random.nextInt(26);
            stringBuilder.append(i1);
        }
        return stringBuilder.toString();
    }

    public static byte[] byteRowKey() {
        return ByteUtil.toBytes(rowKey());
    }

    public static String odsTableName(String business, String table) {
        return "ODS_" + business + "_" + table;
    }

    public static List<ResultRow> convertToResultRow(Map<String, List<String>> hbaseResult) {
        int colNum = hbaseResult.size();
        ResultRow[] resultRows = null;
        int colIndex = 0;
//        ResultRow resultRow = new ResultRow(colNum);
        boolean init = false;
        for (Map.Entry<String, List<String>> entry : hbaseResult.entrySet()) {
            String colName = entry.getKey();
            List<String> colDataList = entry.getValue();
            if (!init) {
                int rowNum = colDataList.size();
                resultRows = new ResultRow[rowNum];
                init = true;
            }
            int rowIndex = 0;
            for (String colValue : colDataList) {
                ResultData data = new ResultData();
                data.setColumnName(colName);
                data.setColumnValue(colValue);
                if (resultRows[rowIndex] == null) {
                    resultRows[rowIndex] = new ResultRow(colNum);
                }
                //添加这一行的列数据
                resultRows[rowIndex].add(data);
                rowIndex++;
            }
            colIndex++;
        }
        if (resultRows == null) {
            resultRows = new ResultRow[0];
        }
        return Arrays.asList(resultRows);
    }
}
